<template>
  <el-header>
    <div class="l-content">
      <!-- 图标的展示 -->
      <el-button size="small" @click="handleCollapse">
        <el-icon :size="20">
          <!-- el图标库 -->
          <Menu />
        </el-icon>
      </el-button>
      <el-breadcrumb separator="/" class="bread">
        <!-- 首页 -->
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item
          v-for="(item, index) in currentMenuList"
          :key="index"
        >
          <span
            v-if="index == currentMenuList.length - 1"
            class="no-redirect"
            >{{ item.label }}</span
          >
          <span v-else class="redirect">{{ item.label }}</span>
        </el-breadcrumb-item>
        <!-- <el-breadcrumb-item :to="current.path" v-if="current">{{
          current.label
        }}</el-breadcrumb-item> -->
      </el-breadcrumb>
    </div>
    <div class="r-content">
      <el-dropdown>
        <span class="el-dropdown-link">
          <span class="und">{{ userNameData }}</span>
          <!-- 动态传参获取图片getImageUrl('user') -->
          <img
            v-if="imageUrl"
            :src="imageUrl"
            alt="图片加载中"
            class="user"
            @error="handleImageError"
          />
          <img v-else :src="getImageUrl()" alt="" class="user" />

          <!-- <el-icon size="20px" style="color: #48494b; margin-left: 3px"
            ><CaretBottom
          /></el-icon> -->
        </span>

        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item icon="UserFilled" @click="openPerson"
              >个人中心</el-dropdown-item
            >
            <el-dropdown-item icon="SwitchButton" @click="handleUserClose"
              >退出</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <!-- 个人信息页抽屉 -->
    <el-drawer
      v-model="drawer2"
      :direction="direction"
      :before-close="handleClose"
    >
      <template #header>
        <h2 style="font-weight: bold">个人信息页</h2>
      </template>
      <template #default>
        <el-form
          :inline="false"
          :model="personInfo"
          :rules="rules"
          ref="personForm"
        >
          <el-form-item
            style="margin-bottom: 5px"
            label="请上传头像："
          ></el-form-item>
          <!-- @change="handleChange" -->
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :http-request="uploadImage"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <el-form-item
            label="权&nbsp&nbsp&nbsp限:"
            prop="rule"
            style="margin-top: 13px; margin-left: 9px"
            class="efi"
          >
            <el-input
              v-model="personInfo.roleName"
              placeholder="等级"
              disabled
            />
          </el-form-item>
          <el-form-item label="用户名:" prop="UserName" class="efi">
            <el-input
              class="ei_1"
              v-model="personInfo.userName"
              placeholder="用户名"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="密&nbsp&nbsp&nbsp码:"
            prop="Password"
            class="efi"
            style="margin-left: 9px"
          >
            <el-input
              v-model="personInfo.Password"
              placeholder="请输入修改密码，不必须填写"
              clearable
              show-password
            />
          </el-form-item>
          <el-form-item label="邮&nbsp&nbsp&nbsp箱:" prop="email" class="efi">
            <el-input v-model="personInfo.email" placeholder="邮箱" clearable />
          </el-form-item>
          <el-form-item label="电&nbsp&nbsp&nbsp话:" prop="phone" class="efi">
            <el-input v-model="personInfo.phone" placeholder="电话" clearable />
          </el-form-item>
          <el-form-item label="性&nbsp&nbsp&nbsp别:" prop="sex" class="efi">
            <el-radio-group v-model="personInfo.gender">
              <el-radio label="1">男</el-radio>
              <el-radio label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="生&nbsp&nbsp&nbsp日:"
            prop="birthday"
            class="efi"
          >
            <div class="block">
              <el-date-picker
                v-model="personInfo.birthday"
                type="date"
                placeholder="出生日期"
                value-format="YYYY-MM-DD"
                clearable
              />
            </div>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div>
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="confirmClick">提交</el-button>
        </div>
      </template>
    </el-drawer>
  </el-header>
</template>
<script>
import { useStore } from "vuex";
import {
  ref,
  computed,
  reactive,
  getCurrentInstance,
  onMounted,
  watch,
} from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import config from "../configs/requestindex";
import { all } from "underscore";

export default {
  setup() {
    let store = useStore();
    // let ws = useWebsocket();
    let router = useRouter();
    const { proxy } = getCurrentInstance();
    const userInit = ref("user");
    let getImageUrl = () => {
      //   console.log(import.meta.url);
      //   console.log(new URL("../assets/images/user.png", import.meta.url));
      return new URL(`../assets/images/${userInit.value}.png`, import.meta.url)
        .href;
    };
    // 操作vuex store中的moutations来改变state值
    let handleCollapse = () => {
      store.commit("updateIsCollapse");
    };
    // 面包屑菜单全路径获取
    const allMenuList = ref([]);
    const getAllMenu = () => {
      let allMenuData = JSON.parse(localStorage.getItem("menu"));
      allMenuData.map((item) => {
        getChildrenMenu(item);
      });
    };
    const getChildrenMenu = (item) => {
      allMenuList.value.push(item);
      if (item.children !== null) {
        item.children.map((item) => {
          getChildrenMenu(item);
        });
      }
    };

    const currentMenuList = ref([]);
    const gutCurrentMenu = (newVal) => {
      currentMenuList.value = [];
      getParentMenu(newVal);
    };
    // 递归获取当前菜单的父级菜单，并且从开头放入数组中，用于for遍历展示
    const getParentMenu = (current) => {
      currentMenuList.value.unshift(current);
      allMenuList.value.map((item) => {
        if (item.id === current.parentId) {
          getParentMenu(item);
        }
      });
    };
    // 监听当前菜单改变，触发面包屑改变
    watch(
      () => store.state.currentMenu,
      (newValue) => {
        if (newValue != null) {
          gutCurrentMenu(newValue);
        }
      },
      {
        deep: true,
      }
    );
    // 计算属性
    const current = computed(() => {
      return store.state.currentMenu;
    });
    const userNameData = ref("");
    // 退出登录
    const handleUserClose = () => {
      // 清空菜单
      store.commit("clearMenu");
      // 清空token
      store.commit("clearToken");
      // 断开websocket链接
      store.commit("setwebsocketClose", true);
      router.push({
        name: "login",
      });
    };

    // 个人信息页关闭
    const drawer2 = ref(false);
    // 右侧展开
    const direction = ref("rtl");
    // let personInfo = reactive({
    //   UserName: "",
    //   Password: "",
    //   email: "",
    //   phone: "",
    //   sex: "",
    //   birthday: "",
    //   rule: "",
    // });
    let personInfo = ref();
    // 表单校验
    const rules = reactive({
      UserName: [
        {
          required: true,
          message: "请输入用户名",
          trigger: "blur",
        },
      ],
      Password: [
        {
          required: false,
          message: "请输入密码",
          trigger: "blur",
        },
        {
          min: 6,
          max: 20,
          message: "密码长度在6-20之间",
          trigger: "blur",
        },
      ],
      email: [
        {
          trigger: "blur",
          message: "请填写邮箱信息",
          required: true,
        },
      ],
      phone: [
        {
          required: true,
          message: "请输入手机号",
          trigger: "blur",
        },
        {
          min: 11,
          max: 11,
          message: "请输入11位手机号",
          trigger: "blur",
        },
      ],
      sex: [
        {
          trigger: "change",
          message: "请选择性别",
          required: true,
        },
      ],
      birthday: [
        {
          trigger: "change",
          message: "请选择生日",
          required: true,
        },
      ],
    });
    // 图片展示路径
    const imageUrl = ref();
    //点击打开个人信息
    const openPerson = () => {
      drawer2.value = true;
    };
    //   点击x号关闭个人信息页
    const handleClose = () => {
      drawer2.value = false;
      proxy.$refs.personForm.resetFields();
    };
    // 图片上传请求
    const uploadImage = async (options) => {
      console.log(options);
      let formData = new FormData();
      formData.append("file", options.file);
      formData.append("username", localStorage.getItem("username"));
      console.log("for", formData);
      const res = await proxy.$api.user.uploadImage(formData);
      if (res && res.data.path.length > 0) {
        imageUrl.value = config.baseApi + res.data.path;
        console.log(imageUrl.value);
      }
    };
    const handleAvatarSuccess = (res) => {
      console.log(res);
    };
    // 加载获取用户信息
    onMounted(() => {
      getPersonInfo().then((element) => {
        personInfo.value = element;
        // 如果返回图片路径在拼接路径
        if (element.headPhotoPath !== null) {
          imageUrl.value = config.baseApi + element.headPhotoPath;
        }
      });
      getAllMenu();
    });
    // 获取用户名
    const UserName = localStorage.getItem("username");
    const userId = localStorage.getItem("userId");
    userNameData.value = UserName;
    // 使用用户名请求用户信息
    const getPersonInfo = async () => {
      const res = await proxy.$api.user.getPersonInfo({ userId: userId });
      if (res) {
        const rulesMap = {
          1: "管理员",
          2: "普通用户",
        };

        // 处理数据
        const { gender } = res.data;
        res.data.gender = gender === 1 ? "1" : "0";
        console.log(res.data);
        return res.data;
      }
    };
    // 取消按钮
    const cancelClick = () => {
      drawer2.value = false;
      proxy.$refs.personForm.resetFields();
    };
    // 确认提交
    const confirmClick = () => {
      proxy.$refs.personForm.validate(async (valid) => {
        if (valid) {
          let personPassword = personInfo.value.Password;
          // 如果密码修改的话就进行加密保存
          if (
            personInfo.value.Password !== null &&
            personInfo.value.Password !== ""
          ) {
            personPassword = await proxy.$md5(personInfo.value.Password);
          } else {
            personPassword = null;
          }
          let personInfoData = {
            id: personInfo.value.id,
            UserName: personInfo.value.UserName,
            Password: personPassword,
            sex: personInfo.value.sex,
            birthday: personInfo.value.birthday,
            phone: personInfo.value.phone,
            email: personInfo.value.email,
            HeadPhotoPath: personInfo.value.HeadPhotoPath,
            rule: personInfo.value.rule,
          };
          let res = await proxy.$api.updateUserData(personInfoData);
          if (res) {
            ElMessage.success(res.message);
            proxy.$refs.personForm.resetFields();
            drawer2.value = false;
            getPersonInfo().then((res) => {
              res.forEach((element) => {
                personInfo.value = element;
                if (element.HeadPhotoPath !== null) {
                  imageUrl.value = config.baseApi + element.HeadPhotoPath;
                }
              });
            });
            // setTimeout(() => {
            //   ElMessage.warning("请重新登录");
            //   router.push({
            //     name: "login",
            //   });
            // }, 2000);
          }
        } else {
          ElMessage.error("请填写完整信息");
        }
      });
    };
    // 图片上传限制
    const beforeAvatarUpload = (file) => {
      const types = ["image/jpeg", "image/png"];
      const isType = types.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isType) {
        ElMessage.error("上传头像图片只能是 JPG活PNG 格式!");
      }
      if (!isLt2M) {
        ElMessage.error("上传头像图片大小不能超过 2MB!");
      }
      return isType && isLt2M;
    };
    // 图片请求资源404提示
    const handleImageError = () => {
      ElMessage.error("用户头像资源丢失，请重新上传头像");
      imageUrl.value = "";
    };

    return {
      getImageUrl,
      handleCollapse,
      currentMenuList,
      handleUserClose,
      confirmClick,
      cancelClick,
      openPerson,
      direction,
      drawer2,
      personInfo,
      uploadImage,
      imageUrl,
      rules,
      handleAvatarSuccess,
      handleClose,
      beforeAvatarUpload,
      handleImageError,
      userNameData,
    };
  },
};
</script>
<style lang="less" scoped>
header {
  display: flex;
  //   主抽对齐方式
  justify-content: space-between;
  //   交叉轴对齐方式
  align-items: center;
  width: 100%;
  // background: #ffb900;
  background-color: #ffffff;
  // 渐变色
  background-image: linear-gradient(90deg, #ffffff 0%, #8eb7f9 100%);
  height: 47px;
  box-shadow: 3px 3px 6px rgba(0, 0, 0, 0.1); /* 设置阴影 */
}
.r-content {
  .user {
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }
  .el-dropdown-link {
    outline: none;
    display: flex;
    align-items: center;
    height: 100%;
    .und {
      font-size: 18px;
      font-family: sans-serif;
      color: #4c535e;
      margin-right: 8px;
      margin-top: auto;
      margin-bottom: auto;
    }
  }
}
.l-content {
  display: flex;
  align-items: center;
  .el-button {
    margin-right: 20px;
  }
  // h3 {
  //   color: aliceblue;
  // }
}
// :deep(.bread span) {
//   color: #272727 !important;
//   cursor: pointer !important;
// }
:deep(.avatar-uploader) {
  margin-left: 65px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
:deep(.el-form-item__content) {
  flex: none !important;
  width: 220px !important;
}
:deep(.el-drawer__body) {
  margin-left: 30px;
}
.ei_1 {
  margin-left: -2px !important;
}

.no-redirect {
  color: #97a8be;
  cursor: text;
}
.redirect {
  color: #272727;
  cursor: text;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
